<template>
  <div class="dragbox">
    <el-divider content-position="center">工艺明细信息</el-divider>
    <div style="margin-bottom: 5px">
      <el-button icon="Plus" type="primary" class="button" @click="addCarTechnologyDetail">新增</el-button>
      <el-button icon="delete" type="danger" class="button" @click="deleteCarTechnologyDetails">删除</el-button>
    </div>
    <el-table :data="carTechnologyDetails" border style="width: 100%" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="materialName" label="物料" width="200">
        <template #default="scope">
          <el-form-item label-width="0" :prop="'carTechnologyDetails.' + scope.$index + '.materialId'" :rules="detailRule.materialId">
            <el-select v-model="scope.row.materialId" value-key="id" @change="materialChange($event, scope.row)" clearable placeholder="请选择物料">
              <el-option v-for="(item, index) in materials" :key="index" :label="item['name']" :value="item['id']"></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="materialModel" label="物料型号" width="180">
        <template #default="scope">
          <el-form-item label-width="0">
            <template v-if="scope.row.material != undefined">
              <el-input v-model="scope.row.material.model" disabled />
            </template>
            <template v-else>
              <el-input disabled />
            </template>
            <!-- {{ scope.row.material !== undefined ? scope.row.material.model : '' }} -->
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="materialSpecification" label="物料规格" width="180">
        <template #default="scope">
          <el-form-item label-width="0">
            <template v-if="scope.row.material != undefined">
              <el-input v-model="scope.row.material.specification" disabled />
            </template>
            <template v-else>
              <el-input disabled />
            </template>
            <!-- {{ scope.row.material !== undefined ? scope.row.material.model : '' }} -->
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="materialPrice" label="物料单价" width="180">
        <template #default="scope">
          <el-form-item label-width="0">
            <template v-if="scope.row.material != undefined">
              <el-input v-model="scope.row.material.price" disabled />
            </template>
            <template v-else>
              <el-input disabled />
            </template>
            <!-- {{ scope.row.material !== undefined ? scope.row.material.model : '' }} -->
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="materialPrice" label="物料库存" width="180">
        <template #default="scope">
          <el-form-item label-width="0">
            <template v-if="scope.row.material != undefined">
              <el-input v-model="scope.row.material.inventory" disabled />
            </template>
            <template v-else>
              <el-input disabled />
            </template>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" width="180">
        <template #default="scope">
          <el-form-item label-width="0" :prop="'carTechnologyDetails.' + scope.$index + '.quantity'" :rules="detailRule.quantity">
            <el-input v-model.number="scope.row.quantity" placeholder="请输入物料数量" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="工序" width="180">
        <template #default="scope">
          <el-form-item label-width="0">
            <el-select v-model="scope.row.sort" placeholder="请选择工序" @change="sortChange($event, scope.$index)">
              <el-option v-for="number in carTechnologyDetails.length" :key="number" :label="number" :value="number" />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
//导入拖拽插件
// import draggable from 'vuedraggable';
import Sortable from 'sortablejs';
import urls from '@/api/request/urls';
import type { CarTechnologyDetail, Material } from '@/types/interface/mes_interface';
import { nextTick, onMounted, ref } from 'vue';
import Request from '@/api/request/request';
import { ElMessage, ElMessageBox } from 'element-plus';

//工艺明细模块===============================================================
//接收父组件表单的工艺详情列表
const carTechnologyDetails = defineModel<CarTechnologyDetail[]>({
  required: false,
  default: []
});
//工艺明细的表单验证规则
const detailRule = {
  materialId: [{ required: true, message: '不能为空', trigger: 'change' }],
  quantity: [
    { required: true, message: '不能为空', trigger: 'blur' },
    { type: 'number', message: '必须为数字值' }
  ]
};
//全选按钮动作
const multipleSelection = ref<CarTechnologyDetail[]>([]); // 复选框选择的记录row
const handleSelectionChange = (selection: CarTechnologyDetail[]) => {
  // 当选择项发生变化时会触发该事件，这里用于获取选择的记录（多选）.value可以获取所有选择了的行记录row
  multipleSelection.value = selection;
};
//删除多个详情
const deleteCarTechnologyDetails = async (): Promise<void> => {
  if (multipleSelection.value.length > 0) {
    ElMessageBox.confirm(`确定要删除这${multipleSelection.value.length}个记录吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        //遍历复选框选中的集合
        for (let carTechnologyDetailSelect of multipleSelection.value) {
          //删除被选中的元素
          carTechnologyDetails.value = carTechnologyDetails.value.filter((item) => item.sort !== carTechnologyDetailSelect.sort);
          //等待DOM删除完成，必须要加。
          await nextTick();
        }
        //清空选中元素
        multipleSelection.value.length == 0;
        //重新排序
        await sortCarTechnologyDetails(0);
      })
      .catch(() => {
        // 点击了取消按钮
      });
  } else {
    ElMessage.error('请至少选择一条数据');
  }
};
//物料列表
const materials = ref<Material[]>([]);
const getMaterials = async (name: string) => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_MES_MATERIAL + '/all', null, { params: { name: name } }).get();
  if (resData.success) {
    return resData.data;
  }
};
onMounted(async () => {
  materials.value = await getMaterials('');
  //页面加载就执行拖拽函数
  rowDrop();
});
//添加新的表单记录
const addCarTechnologyDetail = () => {
  //获取最后一个元素的排序
  let sort = 1; //默认从0开始
  if (carTechnologyDetails.value.length > 0) {
    //获取最后一个元素的值
    const carTechnologyDetailLast: CarTechnologyDetail = carTechnologyDetails.value[carTechnologyDetails.value.length - 1];
    sort = carTechnologyDetailLast.sort! + 1;
  }
  let carTechnologyDetailNew: CarTechnologyDetail = {
    id: sort.toString(),
    sort: sort
  };
  carTechnologyDetails.value.push(carTechnologyDetailNew);
};
//对表单详情进行重新排序
const sortCarTechnologyDetails = async (index: number) => {
  if (index === undefined) {
    index = 0;
  }
  for (; index < carTechnologyDetails.value.length; index++) {
    carTechnologyDetails.value[index].sort = index + 1;
    //等待DOM值改变
    await nextTick();
  }
};
//远程获取物料列表
// const materialSelectloading = ref(false); //物料下拉框加载状态
// const remoteGetMaterials = async (query: string) => {
//   if (query) {
//     materialSelectloading.value = true;
//     materials.value = await getMaterials('');
//     materialSelectloading.value = false;
//   } else {
//     materials.value = [];
//   }
// };
/**
 * 当物料下拉框发生变化时
 * @param materialId 选中的物料id
 * @param carTechnologyDetail 所在行的对象地址
 */
const materialChange = async (materialId: string, carTechnologyDetail: CarTechnologyDetail) => {
  if (materialId !== undefined && materialId.length > 0) {
    //给表格中的物料其他字段设置值
    for (const materialOfEach of materials.value) {
      if (materialOfEach.id === materialId) {
        carTechnologyDetail.material = materialOfEach;
      }
    }
  } else {
    //如果被清空了
    carTechnologyDetail.material = undefined;
  }
};
//当排序的值发生改变，对顺序进行调换。第一个参数：改变后的sort值；第二个参数：所在数组carTechnologyDetails位置
const sortChange = async (sort: number, index: number) => {
  //1.与改动后的其他元素调换位置
  let temp = carTechnologyDetails.value[index];
  carTechnologyDetails.value[index] = carTechnologyDetails.value[sort - 1];
  carTechnologyDetails.value[sort - 1] = temp;
  //从index开始重新排序
  await sortCarTechnologyDetails(index);
};
// 行拖拽，表示哪些部分可以拖拽。注意，使用这个拖动插件必须在表格加合适的row-key属性，否则会导致虚拟表与真是表不同
//当拖动的时候，要保持顺序
const rowDrop = () => {
  const tbody = document.querySelector('.dragbox .el-table__body-wrapper tbody');
  Sortable.create(tbody, {
    draggable: '.dragbox .el-table__row',
    async onEnd(evt: any) {
      //1.与改动后的其他元素调换位置.
      let temp = carTechnologyDetails.value[evt.oldIndex];
      let sortOfOld = temp.sort;
      let sortOfNew = carTechnologyDetails.value[evt.newIndex].sort;
      //1.1 让元素位置交换，原来的元素改为新位置的 元素
      carTechnologyDetails.value[evt.oldIndex] = carTechnologyDetails.value[evt.newIndex];
      //1.2 新位置的元素变为原来位置的元素
      carTechnologyDetails.value[evt.newIndex] = temp;
      //1.3 排序不进行交换，即保持不变
      carTechnologyDetails.value[evt.newIndex].sort = sortOfNew;
      carTechnologyDetails.value[evt.oldIndex].sort = sortOfOld;
      //获取当前行的值，并移除原来的记录
      //   const currentRow = carTechnologyDetails.value.splice(evt.oldIndex, 1)[0];
      //在新的位置加上原来的记录
      //   carTechnologyDetails.value.splice(evt.newIndex, 0, currentRow);
      //   console.log(carTechnologyDetails.value);
    }
  });
};
</script>

<style scoped></style>
